<template>
  <el-drawer direction="ltr" v-model="drawer" title="Word Definition" :with-header="true" size="100%"
    class="custom-drawer" style="padding-left: 3%; color: var(--btn-text); background: var(--bg-color);" :model="false">
    <div class="container">

      <div class="word-definition">
        <!-- 词典 API 加载状态 -->
        <div v-if="loadingDictionary" class="loading-container">
          <el-icon class="loading-icon">
            <loading />
          </el-icon> 正在加载词典数据...
        </div>
        <div v-else-if="errorMessage" class="error-message">{{ errorMessage }}</div>

        <!-- 词典 API 结果 -->
        <div v-else-if="result" class="dictionary-result">
          <h2>{{ result.word }}</h2>
          <p v-if="phonetic">🔊 音标: {{ phonetic }}</p>

          <div v-for="(meaning, index) in result.meanings" :key="index">
            <h3>{{ meaning.partOfSpeech }}</h3>
            <ul>
              <li v-for="(definition, idx) in meaning.definitions" :key="idx">
                <p>📖 {{ definition.definition }}</p>
                <p v-if="definition.example">💡 示例: "{{ definition.example }}"</p>
              </li>
            </ul>
          </div>

          <audio v-if="audio" :src="audio" controls></audio>

          <div class="source-links">
            <h4>🔗 参考资料:</h4>
            <ul>
              <li v-for="(link, i) in result.sourceUrls" :key="i">
                <a :href="link" target="_blank">{{ link }}</a>
              </li>
            </ul>
          </div>
        </div>

        <!-- AI 解析 -->
        <div class="ai-container">
          <!-- AI 解析加载状态（带动画） -->
          <div v-if="loadingAi" class="loading-container">
            <el-icon class="loading-icon">
              <loading />
            </el-icon>
            <span class="loading-text">正在请求 AI 解析...</span>
          </div>

          <!-- AI 解析结果 -->
          <div v-else-if="aiExplanation" class="ai-card">
            <h3 class="ai-title">🤖 AI 解析</h3>
            <p class="ai-content" v-html="aiExplanation"></p>
          </div>

          <!-- AI 解析失败 -->
          <el-alert v-else-if="aiError" title="AI 解析失败" type="error" show-icon class="ai-error">
            ⚠️ AI 解析出错，请稍后重试。
          </el-alert>
        </div>
      </div>
      <div class="translate-container">

      </div>
      <div class="translate-containerFlag">
        <Translate />
      </div>
    </div>

  </el-drawer>
</template>

<script setup>
import { ref, defineProps, watch, onMounted } from "vue";
import axios from "axios";
import { marked } from "marked";
import { Loading } from "@element-plus/icons-vue";
import Translate from './translate.vue'



// 接收父组件传递的 `word`
const props = defineProps({
  word: String,
  show: Boolean
});
// console.log(props.word, 'props.word');
const drawer = ref(props.show);
const result = ref(null);
const errorMessage = ref("");
const audio = ref(null);
const phonetic = ref("");

const loadingDictionary = ref(false);
const loadingAi = ref(false);
const aiExplanation = ref("");
const aiError = ref(false);

// 监听 `show` 变化，控制 `drawer` 显示
watch(() => props.show, async (newValue) => {
  drawer.value = newValue;
  if (newValue && props.word) {
    fetchWordDefinition(props.word); // 词典 API
    fetchAiExplanation(props.word); // AI 解析 API
  }
});

// 获取单词定义（词典 API）
const fetchWordDefinition = async (word) => {
  errorMessage.value = "";
  result.value = null;
  audio.value = null;
  phonetic.value = "";
  loadingDictionary.value = true;

  try {
    const response = await axios.get(`https://api.dictionaryapi.dev/api/v2/entries/en/${word}`);
    const data = response.data[0];
    result.value = data;
    phonetic.value = data.phonetic || (data.phonetics[0]?.text ?? "");

    // 获取发音音频
    const sound = data.phonetics.find((p) => p.audio);
    if (sound) {
      audio.value = sound.audio;
    }
  } catch (error) {
    errorMessage.value = `❌ 未找到 ${word}，请检查拼写！`;
  } finally {
    loadingDictionary.value = false;
  }
};

// 获取 AI 解析（独立执行）
const fetchAiExplanation = async (word) => {
  aiExplanation.value = "";
  loadingAi.value = true;
  aiError.value = false;

  try {
    const requestBody = {
      messages: [
        { role: "system", content: "你是一个专业的词典助手，请对给定单词提供详细解释，包括用法、例句等。" },
        { role: "user", content: `请解释单词 ${word} 的详细用法、例句和短语。用150个文字` }
      ]
    };

    const aiResponse = await axios.post("http://localhost:3000/ai-chat", requestBody);

    if (aiResponse.data && aiResponse.data.choices) {
      aiExplanation.value = marked(aiResponse.data.choices[0].message.content);
    }
  } catch (error) {
    console.error("AI API 请求失败:", error);
    aiError.value = true;
  } finally {
    loadingAi.value = false;
  }
};


onMounted(() => {
  console.log(props.word, 'detailedWord.vue');
  fetchWordDefinition(props.word); // 词典 API
  fetchAiExplanation(props.word); // AI 解析 API
});



import { inject } from "vue";

const theme = inject("theme");
const setTheme = (newTheme) => {
  theme.value = newTheme; // 更新全局主题
};


</script>

<style scoped>
/* :root {
  --common-width: 80%;
} */


/* .custom-drawer {} */

.container {
  --common-width: 70%;
  --translate-width: 20%;
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.translate-container {

  width: 30%;
}

.translate-containerFlag {
  width: var(--translate-width);
  height: 40vh;
  position: fixed;
  top: 5vh;
  right: 3vw;
  display: block;
}

.word-definition {
  width: var(--common-width);
}

.custom-drawer h2 {
  margin: 12px 0;
}

.custom-drawer h3 {
  margin: 10px 0;
}

.custom-drawer p {
  margin: 8px 0;
}

.custom-drawer ul {
  padding-left: 20px;
}

.custom-drawer .source-links {
  margin-top: 16px;
}

.ai-container {
  margin-top: 20px;
  padding: 15px;
  border-radius: 8px;
  background: var(--bg-light, var(--bg-color-diff));
  /* width: var(--common-width); */
}

/* .dictionary-result {
  
} */

.loading-container {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 16px;
  color: #007bff;
  /* width: var(--common-width); */
}

.loading-icon {
  font-size: 20px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

/* AI 解析整体容器 */
.ai-container {
  margin-top: 16px;
  padding: 12px;
}

/* 加载动画容器 */
.loading-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 16px;
  color: var(--btn-text);
  animation: fadeIn 0.5s ease-in-out;
}

/* 旋转加载动画 */
.loading-icon {
  animation: spin 1.2s linear infinite;
}

/* AI 解析卡片 */
.ai-card {
  background: linear-gradient(var(--bg-color-deg), var(--bg-color-change1), var(--bg-color-change3));
  padding: 16px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

/* AI 解析卡片悬停效果 */
.ai-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

/* AI 解析标题 */
.ai-title {
  font-size: 18px;
  font-weight: bold;
  color: var(--btn-text);
  margin-bottom: 8px;
}

/* AI 解析内容 */
.ai-content {
  font-size: 16px;
  line-height: 1.5;
  color: var(--btn-text);
}

/* AI 解析错误消息 */
.ai-error {
  margin-top: 12px;
}

/* 旋转动画 */
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

/* 渐隐动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}
</style>
